# -*- coding: utf-8 -*-
import pymysql
from paper.utils.config import Config


class Mysql:
    # 初始化
    def __init__(self):
        # 实例化config
        config = Config('mysql')
        db = pymysql.connect(host=config.get(obj='url'), user=config.get(obj='username'),
                             password=config.get(obj='password'),
                             db=config.get(obj='data_base'), port=int(config.get(obj='port')))
        # 使用 cursor() 方法创建一个游标对象 cursor
        cursor = db.cursor()
        self.db = db
        self.cursor = cursor

    # 结果是一个对象集
    def fetch(self, sql, status):
        try:
            # 执行sql语句
            self.cursor.execute(sql)
            result = None
            if status == 'all':
                # 获取所有数据
                result = self.cursor.fetchall()
            elif status == 'one':
                result = self.cursor.fetchone()
            return result
        except pymysql.ProgrammingError as error:
            print(error)

    # 插入数据/更新数据
    def other(self, sql):
        try:
            # 执行sql语句
            self.cursor.execute(sql)
            # 提交到数据库执行
            result = self.db.commit()
            return result
        except ProcessLookupError:
            print('插入数据失败~~')
            self.db.rollback()

    # 销毁
    def __del__(self):
        self.cursor.close()
        self.db.close()
        print('销毁了')
